package com.babel.util.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * CookieUtil
 */
public class CookieUtil {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	public static String get(HttpServletRequest request, String key) {
		Cookie cookie[] = request.getCookies();
		if (cookie == null || cookie.length == 0) {
			return null;
		}
		for (int i = 0; i < cookie.length; i++) {
			if (cookie[i].getName().equals(key)) {
				return cookie[i].getValue();
			}
		}
		return null;
	}

	/**
	 * 设置cookie（当前域名）
	 * @param response
	 * @param key
	 * @param value
	 * @param time
	 * @return
	 */
	public static HttpServletResponse set(HttpServletResponse response, String key, String value, Integer time) {
		Cookie cookie = new Cookie(key, value);
		if (time != null) {
			cookie.setMaxAge(time);
		}
		cookie.setPath("/");
		response.addCookie(cookie);
		return response;
	}
	
	/**
	 * 设置cookie（当前顶级域名）
	 * @param request
	 * @param response
	 * @param key
	 * @param value
	 * @param time
	 * @return
	 */
	public static HttpServletResponse set(HttpServletRequest request, HttpServletResponse response, String key, String value, Integer time) {
		Cookie cookie = new Cookie(key, value);
		if (time != null) {
			cookie.setMaxAge(time);
		}
		String serverName = request.getServerName();
		System.out.println("当前域名为："+serverName);
		boolean res = isIP(serverName);
		if(res){
			cookie.setDomain("caihang.com");
		}else{
			if( serverName.contains(".")){
				String[] str = serverName.split("\\.");
				serverName = str[str.length-2]+"."+str[str.length-1];
			}
			cookie.setDomain(serverName);
		}
		cookie.setPath("/");
		response.addCookie(cookie);
		return response;
	}

	/**
	 * 是否为id
	 * @param addr 字符串
	 * @return  boolean
	 */
	public static boolean isIP(String addr) {
		if(addr.length() < 7 || addr.length() > 15 || "".equals(addr)) {
			return false;
		}
		/**
		 * 判断IP格式和范围
		 */
		String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";

		Pattern pat = Pattern.compile(rexp);

		Matcher mat = pat.matcher(addr);

		return mat.find();

	}


}
